#include "mqtthandler.h"
#include <QTimer>
#include <qmqtt_client.h>
#include "globalval.h"

#define TOPIC_DATA_UP       "up"
#define TOPIC_DATA_DOWN     "/app/data/down"
#define TOPIC_CTL_UP        "/app/control/up"
#define TOPIC_CTL_DOWN      "typedown"
//QString MqttHandler::topic;

MqttHandler::MqttHandler(QObject *parent) : QObject(parent)
{

    GlobalVal::topic = TOPIC_CTL_DOWN;

    // 创建客户端对象，设置客户端id
    client = new QMQTT::Client();
    client->setClientId("home-app");

    connect(client, SIGNAL(connected()), this, SLOT(doConnected()));

    connect(client, SIGNAL(subscribed(QString, quint8)),\
            this, SLOT(doSubscribed(QString, quint8)));

    connect(client,SIGNAL(received(QMQTT::Message)),\
            this,SLOT(doDataReceived(QMQTT::Message)));
}

// 连接mqtt服务器函数
void MqttHandler::connectToHost()
{
    client->connectToHost();

    //3s后检测一下连接状态
    QTimer::singleShot(3000, this, SLOT(detectState()));
}

void MqttHandler::detectState()
{
    int state = client->connectionState();
    if(state != 2)  //STATE_CONNECTED引用不到，很奇怪
    {
        qDebug()<<"mqtt connect error";
    }
}

/**
 * @brief 连接以后再订阅相关的主题
 */
void MqttHandler::doConnected()
{
    qDebug()<<"mqtt connect ok";
    client->subscribe(TOPIC_DATA_UP);
    client->subscribe(TOPIC_CTL_UP);
}

//订阅成功后调用，打印订阅的主题。
void MqttHandler::doSubscribed(const QString& topic, const quint8 qos)
{
    qDebug()<<"subscribed ok, topic="<<topic;
}

//处理接收到的消息，根据消息主题触发相应的信号 dataUpSignal 或 ctrlUpSignal。
void MqttHandler::doDataReceived(QMQTT::Message message)
{
    qDebug()<<"topic="<<QString(message.topic());
    qDebug()<<"payload="<<QString(message.payload());


    if(message.topic() == TOPIC_DATA_UP)
    {
        qDebug()<<"data up topic";
        QByteArray mqttarray = message.payload();
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(mqttarray, &jsonError);  // 转化为 JSON 文档
        QJsonObject object = doucment.object();  // 获取根对象

        if(object.contains("timeData"))
        {
            qDebug() << "这是历史数据" ;
            emit hissignal(message.payload());
            qDebug() << "发送成功" ;
        }
        else
        {
            qDebug() << "这是上报数据" ;
            emit dataUpSignal(message.payload());
            qDebug() << "发送成功" ;
        }


    }
    else if(message.topic() == TOPIC_CTL_UP)
    {
        qDebug()<<"ctrl up topic";
        emit ctrlUpSignal(message.payload());
    }
}

//发布消息到 MQTT 服务器。
quint16 MqttHandler::publish(const QMQTT::Message &message)
{
    client->publish(message);
}
